package com.homedo.microservice.open.service.gateway.manager.web.filter;

import com.homedo.common.dao.autoconfig.DbConfig;
import com.homedo.common.dao.conf.DataSourceChooseSupportHolder;
import com.homedo.common.util.Detect;
import com.homedo.common.util.support.UserContextHolder;
import com.homedo.microservice.open.service.gateway.manager.web.gateway.support.ApplicationNameHolder;
import com.netflix.turbine.discovery.InstanceObservable;
import com.netflix.turbine.plugins.PluginsFactory;

import javax.servlet.*;
import java.io.IOException;

public class SetGategayInfoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String dataSourceName = DbConfig.DEAFULT_DATA_SOURCE_NAME;
        String gateway = request.getParameter("gateway");
        String env = request.getParameter("env");
        if (Detect.notEmpty(gateway) && Detect.notEmpty(env)) {
            dataSourceName = gateway + "_" + env;
        }
        try {
            DataSourceChooseSupportHolder.set(dataSourceName);
            ApplicationNameHolder.set(gateway);
            chain.doFilter(request, response);
        } finally {
            DataSourceChooseSupportHolder.reset();
            ApplicationNameHolder.reset();
            UserContextHolder.resetUsercontext();
        }
    }

    @Override
    public void destroy() {
        InstanceObservable.getInstance().stop();
        PluginsFactory.getClusterMonitorFactory().shutdownClusterMonitors();
    }
}
